#!/bin/bash
#********************************************************************
# Author: zhangjunjie
# Date: 2022-06-23
# FileName：centos_install_php.sh
#********************************************************************

### ----------- 源码安装常量的位置 ----------- ###
SRC_DIR='/usr/local/src'
PHP_VERSION="7.4.11"
PHP_DIR="php-${PHP_VERSION}"
PHP_FILE="${PHP_DIR}.tar.xz"
PHP_DOWN_URL="https://www.php.net/distributions/${PHP_FILE}"
PREFIX="/apps/`echo $PHP_DIR | tr . '_'`"
### ----------- 源码安装常量的位置 ----------- ###
cd $SRC_DIR

## 先判断是否存在自定义的方法文件, 如果不存在, 则进行下载操作
if [ ! -e self_function.sh ]; then
	rpm -q wget || (yum install wget -y || { echo -e "\E[31;1m 安装 wget 软件包失败 \E[0m" ; exit; })

	echo -e "\E[33;1m 下载自定义方法中 \E[0m"
	wget https://gitee.com/gkdaxue/shell_script/raw/master/self_function.sh
	if [ ! -e self_function.sh ]; then 
		echo -e "\E[31;1m 下载自定义方法失败 \E[0m"
		exit;
	fi
fi

## 加载自定义方法
. ./self_function.sh
actions 'echo_tips' "加载自定义方法";

## 判断存不存在安装文件
if [ ! -e $PHP_FILE ]; then
	actions 'echo_tips' "PHP 源码文件不存在， 正在下载中， 请稍后"
	wget $PHP_DOWN_URL
	[ ! -e  $PHP_FILE ] || { actions 'echo_error' '文件下载失败, 请稍后重试'; exit; }
elif [ -e $PREFIX ]; then
	actions 'echo_error' "安装目录已经存在, 请确认 php 是否安装, 即将退出"
	exit;
fi

useradd -s /sbin/nologin -r www

yum -y install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel

mkdir -p $PREFIX/log
tar xvf $PHP_FILE
cd $PHP_DIR
./configure --prefix=${PREFIX} \
	--enable-mysqlnd \
	--with-mysqli=mysqlnd \
	--with-pdo-mysql=mysqlnd \
	--with-openssl \
	--with-zlib \
	--with-config-file-path=/etc \
	--with-config-file-scan-dir=/etc/php.d \
	--enable-mbstring \
	--enable-xml \
	--enable-sockets \
	--enable-fpm \
	--enable-maintainer-zts \
	--disable-fileinfo

make && make install
cp $SRC_DIR/$PHP_DIR/php.ini-production /etc/php.ini
cd $PREFIX
cp etc/php-fpm.conf.default etc/php-fpm.conf
cp etc/php-fpm.d/www.conf.default etc/php-fpm.d/www.conf

sed -i -e '/^user = nobody/c user = www' \
	-e '/^group = nobody/c group = www' \
	-e "/^;pm.status_path /a pm.status_path = \/pm_status" \
	-e "/^;ping.path/a ping.path = \/ping " \
	-e "/^;access.log/a access.log = log/\$pool.access.log " \
	-e "/^;slowlog/a slowlog = log/\$pool.log.slow" etc/php-fpm.d/www.conf

$PREFIX/sbin/php-fpm -t
cp $SRC_DIR/$PHP_DIR/sapi/fpm/php-fpm.service /usr/lib/systemd/system/
systemctl daemon-reload
systemctl enable php-fpm
systemctl restart php-fpm
actions 'echo_tips' "php-fpm 已经安装成功了"